package cn.hx.whh.automaticticket.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

import cn.hx.whh.automaticticket.R;

public class ReceiveFailActivity extends Activity {
    private TextView time_text;
    private String time_number = "10";
    private Timer timer;
    private TimerTask task;
    private TextView bottom;
    private Handler handler;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive_fail);
        bottom = (TextView) findViewById(R.id.bottom);
        bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                backPrint(view);
            }
        });
        time_text = findViewById(R.id.time_text);
        time_text.setText(time_number);
        this.handler = new Handler(){
            public void handleMessage(Message message) {
                TextView view = (TextView) findViewById(R.id.time_text);
                view.setText(time_number);
            }
        };
    }

    private void switchActivity() {
        startActivity(new Intent(this, IndexActivity.class));
        closeTimer();
    }

    private void setTimeText(int number) {
        time_number = String.valueOf(number);
        //TextView text = (TextView) findViewById(R.id.time_text);
        //text.setText(time_number);
        Message message = new Message();
        handler.handleMessage(message);
    }

    private void init() {
        this.timer = new Timer();
        this.task = new TimerTask() {
            public void run() {
                int number = Integer.parseInt(time_number);
                number--;
                System.out.println("ReceiveSuccessActivity ---> number --> " + number);
                setTimeText(number);
                if (number < 1) {
                    switchActivity();
                }
            }
        };
        timer.schedule(task, 1000, 1000);
    }

    public void backPrint(View view) {
        startActivity(new Intent(this, IndexActivity.class));
        closeTimer();
    }

    private void closeTimer() {
        if (this.timer != null) {
            this.timer.cancel();
            this.timer = null;
        }
        if (this.task != null) {
            this.task.cancel();
            this.task = null;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeTimer();
    }

    @Override
    public void onStop() {
        super.onStop();
        closeTimer();
    }
}